﻿using System.Threading.Tasks;
using Common;
using Common.DataModels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace Extensions.Filters;

public class GlobalExceptionFilter:IAsyncExceptionFilter
{
    private readonly IWebHostEnvironment _env;

    public GlobalExceptionFilter(IWebHostEnvironment env)
    {
        _env = env;
    }
    public Task OnExceptionAsync(ExceptionContext context)
    {
        // 表示异常没有被处理
        if (!context.ExceptionHandled)
        {
            var msg = context.Exception.Message;
            //if (_env.IsDevelopment())
            //{
            //    // 如果是开发环境就天极爱堆栈信息
            //    msg += "\r\n" + context.Exception.StackTrace;
            //}
            // 日志输出
            Log.Error($"{msg}\r\n{context.Exception.StackTrace}");
            context.Result = new ContentResult()
            {
                Content =JsonHelper.SerializeObject(new MessageModel<string?>("", false, 500, msg))
            };
            // 错误被处理了
            context.ExceptionHandled = true;
        }
        // task的返回值
        return Task.CompletedTask;
    }


}